<template>
  <el-drawer :append-to-body="true" title="条件设置" v-model="visible" custom-class="condition_copyer" :show-close="false" :size="550" :before-close="saveCondition">
    <template #header="{ titleId, titleClass }">
      <div class="condition-custom-header">
        <h3 :id="titleId" :class="titleClass">条件设置（{{ conditionConfig.nodeName }}）</h3>
        <el-select v-model="conditionConfig.priorityLevel" placeholder="请选择" v-if="!conditionConfig.def && conditionsConfig.conditionNodes.length > 1">
          <el-option v-for="item in conditionsConfig.conditionNodes.length - 1" :key="item" :label="'优先级' + item" :value="item" />
        </el-select>
      </div>
    </template>
    <div class="condition_content drawer_content">
      <p class="tip">当审批单同时满足以下条件时进入此流程</p>
      <div class="condition-list">
        <div v-for="(item, index) in conditionConfig.conditionList" :key="index" class="condition-item">
          <span class="condition-name ellipsis" :title="item.showName">{{ item.showName }}：</span>
          <div v-if="item.columnId == 0" class="condition-option">
            <el-select v-model="item.optType" placeholder="请选择" style="width: 100%">
              <el-option v-for="{ value, label } in promoterOptTypes" :label="label" :value="value" :key="value" />
            </el-select>
            <p :class="Array.isArray(item.zdy1) && item.zdy1.length > 0 ? 'selected_list' : ''" class="selected" @click.self="addConditionRole(item.zdy1)">
              <el-tag v-for="(item1, index) in item.zdy1" :key="index" closable @close="$func.removeEle(item.zdy1, item1)">{{ operatorMapping.user[item1] }}</el-tag>
              <el-input v-if="item.zdy1.length == 0" placeholder="请选择具体人员" style="width: 100%" @click="addConditionRole(item.zdy1)" />
            </p>
          </div>
          <el-button class="condition-del" type="primary" link @click="handleDeleteCondition(item)">删除</el-button>
        </div>
      </div>
      <el-button type="primary" @click="addCondition">添加条件</el-button>
      <el-dialog title="选择条件" v-if="conditionVisible" v-model="conditionVisible" :width="480" append-to-body class="condition_list">
        <p>请选择用来区分审批流程的条件字段</p>
        <p class="check_box">
          <el-checkbox v-for="item in conditions" :label="item.showName" :key="item.columnId" :checked="hasChecked(item)" @change="handleChangeChecked(item)" />
        </p>
        <template #footer>
          <el-button @click="conditionVisible = false">取 消</el-button>
          <el-button type="primary" @click="sureCondition">确 定</el-button>
        </template>
      </el-dialog>
    </div>
    <template #footer>
      <div class="drawer-footer">
        <el-button type="primary" @click="saveCondition">确 定</el-button>
        <el-button @click="closeDrawer">取 消</el-button>
      </div>
    </template>
    <EmployeesDialog v-model:visible="conditionRoleVisible" :users="checkedUserList" assigneeType="user" @change="sureConditionRole" :isDepartment="true" />
  </el-drawer>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { useStore } from 'vuex'
import { promoterOptTypes, optionList } from '@/utils/flowConst'
import $func from '@/utils/flow'

let conditionVisible = ref(false)
let conditionsConfig = ref({
  conditionNodes: []
})
let conditionConfig = ref({})
let PriorityLevel = ref('')
let conditions = ref([]) // 条件选项
let conditionList = ref([])

let store = useStore()
const operatorMapping = computed(() => store.state.flow.operatorMapping)
let conditionsConfig1 = computed(() => store.state.flow.conditionsConfig1)
let conditionDrawer = computed(() => store.state.flow.conditionDrawer)
let visible = computed({
  get() {
    return conditionDrawer.value
  },
  set() {
    closeDrawer()
  }
})

// 注: conditionsConfig是所有节点配置, 但conditionConfig是直接取到网关节点下的条件节点(根据当前点击的优先级来获取)
watch(conditionsConfig1, val => {
  conditionsConfig.value = val.value
  PriorityLevel.value = val.priorityLevel
  conditionConfig.value = val.priorityLevel ? conditionsConfig.value.conditionNodes[val.priorityLevel - 1] : { conditionList: [] }
})

// 每次点击添加条件,就调用接口获取条件选项,并把当前已选的条件push到conditionList
const addCondition = async () => {
  conditionVisible.value = true
  conditions.value = structuredClone(optionList)
  conditionList.value = conditionConfig.value.conditionList ? structuredClone(conditionConfig.value.conditionList) : []
}

// 判断是否选择了条件
const hasChecked = data => {
  return conditionList.value.some(item => item.columnId == data.columnId)
}

// 取消选择条件
const handleChangeChecked = data => {
  const index = conditionList.value.findIndex(item => item.columnId == data.columnId)
  if (index > -1) {
    conditionList.value.splice(index, 1)
  } else {
    conditionList.value.push(data)
  }
}

// 确定选择(根据选择类型,初始化条件)
const sureCondition = () => {
  for (var i = 0; i < conditionList.value.length; i++) {
    var { columnId } = conditionList.value[i]
    // 判断是否为新增, 新增的才继续
    const checked = conditionConfig.value.conditionList.some(item => item.columnId == columnId)
    if (!checked) {
      conditionConfig.value.conditionList.push(conditionList.value[i])
    }
  }
  conditionConfig.value.conditionList.sort(function (a, b) {
    return a.columnId - b.columnId
  })
  conditionVisible.value = false
}
const saveCondition = () => {
  closeDrawer()
  var a = conditionsConfig.value.conditionNodes.splice(PriorityLevel.value - 1, 1) //截取旧下标
  conditionsConfig.value.conditionNodes.splice(conditionConfig.value.priorityLevel - 1, 0, a[0]) //填充新下标
  conditionsConfig.value.conditionNodes.map((item, index) => {
    item.priorityLevel = index + 1
  })
  conditionsConfig.value.conditionNodes.forEach(item => {
    if (item.def) {
      item.error = false
    } else {
      item.error = $func.conditionStr(item) == '请设置条件'
    }
  })
  store.commit('flow/setConditionsConfig', {
    value: conditionsConfig.value,
    flag: true,
    id: conditionsConfig1.value.id
  })
}
// 删除条件 
const handleDeleteCondition = data => {
  $func.removeEle(conditionConfig.value.conditionList, data, 'columnId')
  handleChangeChecked(data)
}

// 选择发起人
const checkedUserList = ref([])
let conditionRoleVisible = ref(false)
const addConditionRole = users => {
  checkedUserList.value = users ? users : []
  conditionRoleVisible.value = true
}
const sureConditionRole = users => {
  // 找到发起人条件项
  const condition = conditionList.value.find(item => item.columnId == 0)
  condition.zdy1 = users
  conditionRoleVisible.value = false
}
const closeDrawer = () => {
  store.commit('flow/setCondition', false)
}
</script>

<style lang="scss" scoped>
.condition_copyer {
  .condition-custom-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .el-select {
      width: 100px;
    }
  }

  .condition_content {
    p.tip {
      margin: 20px 0;
      width: 510px;
      text-indent: 17px;
      line-height: 45px;
      background: rgba(241, 249, 255, 1);
      border: 1px solid rgba(64, 163, 247, 1);
      color: #46a6fe;
      font-size: 14px;
    }

    .condition-list {
      max-height: 500px;
      overflow-y: scroll;
      margin-bottom: 20px;

      .condition-item {
        position: relative;
        display: flex;
        flex-wrap: nowrap;
        .condition-name {
          flex-shrink: 0;
          width: 60px;
          font-size: 14px;
        }
        .condition-option {
          width: calc(100% - 100px);
        }
        .selected {
          margin-top: 5px;
        }
        .selected_list {
          margin-top: 5px;
          padding-left: 10px;
          border-radius: 4px;
          min-height: 32px;
          border: 1px solid rgba(217, 217, 217, 1);
          word-break: break-word;
        }
        .condition-del {
          position: absolute;
          top: 10px;
          right: 0px;
        }
      }
    }

    .el-button {
      margin-bottom: 20px;
    }
  }
}

.condition_list {
  .el-dialog__body {
    padding: 16px 26px;
  }

  p {
    color: #666666;
    margin-bottom: 10px;

    & > .check_box {
      margin-bottom: 0;
      line-height: 36px;
    }
  }
}
</style>
